﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YJKRevitBase.WinForm;
using YJKExcelFormTool.Kits;

namespace YJKExcelFormTool
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdRefreshDoorWindowLegend : YJKCommandManual
	{
		[DllImport("user32.dll")]
		private static extern void BlockInput(bool Block);

		protected override Result YJKExcute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			List<Group> list = new List<Group>();
			CmdRefreshDoorWindowLegend.m_doc = cmdData.Application.ActiveUIDocument.Document;
			if (CmdRefreshDoorWindowLegend._hWndRevit == null)
			{
                CmdRefreshDoorWindowLegend._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			bool flag = false;
			foreach (Element element in new FilteredElementCollector(CmdRefreshDoorWindowLegend.m_doc, CmdRefreshDoorWindowLegend.m_doc.ActiveView.Id).OfClass(typeof(Group)).ToElements())
			{
				Group group = (Group)element;
				object obj = InsertDataToGroup.ReadInfoFormGroup(CmdRefreshDoorWindowLegend.m_doc, group, "IsDoorWinGroup");
				if (obj != null && obj is bool)
				{
					flag = true;
					list.Add(group);
				}
			}
			if (!flag)
			{
				YJKMessageBox.Show("当前视图没有门窗图例!");
				return Autodesk.Revit.UI.Result.Failed;
			}
			Result result2;
			try
			{
				cmdData.Application.Application.FailuresProcessing += this.OnFailuresProcessing;
				Result result = TableInterface.RefreshDoorWindowLegend(cmdData, CmdRefreshDoorWindowLegend._hWndRevit, list, ref message);
				CmdRefreshDoorWindowLegend.BlockInput(false);
				result2 = result;
			}
			catch (Exception)
			{
				CmdRefreshDoorWindowLegend.BlockInput(false);
				result2 = Autodesk.Revit.UI.Result.Failed;
			}
			return result2;
		}

		private void OnFailuresProcessing(object sender, FailuresProcessingEventArgs e)
		{
			FailuresAccessor failuresAccessor = e.GetFailuresAccessor();
			string transactionName = failuresAccessor.GetTransactionName();
			IList<FailureMessageAccessor> failureMessages = failuresAccessor.GetFailureMessages();
			if (failureMessages.Count == 0)
			{
				e.SetProcessingResult((FailureProcessingResult)0);
				return;
			}
			if (transactionName.Equals("Refresh"))
			{
				foreach (FailureMessageAccessor failureMessageAccessor in failureMessages)
				{
					failuresAccessor.DeleteWarning(failureMessageAccessor);
				}
				e.SetProcessingResult((FailureProcessingResult)1);
				return;
			}
			e.SetProcessingResult((FailureProcessingResult)0);
		}

        public static WindowHandle _hWndRevit;

		private new static Document m_doc;
	}
}
